package com.xazenith.app;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;

/**
 * @author zhou wei
 * @version 0.1
 * @since 2020-11-12
 */
public class AesEncoder {
    private final static String ALG_NAME = "AES";
    private final int bit;
    private final String pwd;
    public AesEncoder(int bit, String pwd) {
        this.bit = bit;
        this.pwd = pwd;
    }

    public AesEncoder(String pwd) {
        this(128, pwd);
    }

    public byte[] encode(byte[] bytes) throws GeneralSecurityException {
        return doEncodeOrDecode(bytes, Cipher.ENCRYPT_MODE);
    }

    public byte[] decode(byte[] bytes) throws GeneralSecurityException {
        return doEncodeOrDecode(bytes, Cipher.DECRYPT_MODE);
    }

    private byte[] doEncodeOrDecode(byte[] bytes, int mode) throws GeneralSecurityException {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(ALG_NAME);
        keyGenerator.init(bit, new SecureRandom(this.pwd.getBytes()));
        SecretKey secretKey = keyGenerator.generateKey();
        byte[] encoded = secretKey.getEncoded();
        SecretKeySpec keySpec = new SecretKeySpec(encoded, ALG_NAME);
        Cipher cipher = Cipher.getInstance(ALG_NAME);
        cipher.init(mode, keySpec);
        return cipher.doFinal(bytes);
    }

}
